import * as fs from 'node:fs/promises';
import * as vscode from 'vscode';
import * as configuration from '../configuration';
import { log } from '../helper/outputChannel';
import { Helper } from '../helper';
import { TornaDocDetail } from '../types/type';

export async function selectOutputDir() {
  const workspace = await Helper.workspace().catch(e => { vscode.window.showErrorMessage(e); });
  if (!workspace) { return; }

  log.show();
  log.info('选择接口代码文件生成目录...');
  const uris = await vscode.window.showOpenDialog({
    canSelectFiles: false,
    canSelectFolders: true,
    canSelectMany: false,
    title: "选择接口代码文件生成目录",
    defaultUri: workspace.uri
  });
  if (!uris?.length) {
    log.info('已取消');
    return;
  }

  const ret = Helper.fsPath(uris[0]).replace(Helper.fsPath(workspace.uri) + '/', '');
  configuration.setDefaultOutputPath(ret);
  return ret;
}

export async function ensureOutputDir(doc?: TornaDocDetail): Promise<string> {
  const dirPath = configuration.getOutputPath(doc) || await selectOutputDir();
  if (!dirPath) { throw new Error('未设置代码输出目录.'); }
  fs.mkdir(dirPath, { recursive: true });
  return dirPath;
}